package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import cn.imvc.app.entities.StorageType;
import cn.imvc.app.repositories.StorageTypeRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
/**
 * 
 * @author zhy
 * @date 2016年7月29日上午10:08:59
 *
 */
@Service
public class StorageTypeModelImpl implements StorageTypeModel{

	@Autowired
	StorageTypeRepository storageTypeRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<StorageType> find(ViewRequest viewRequest) {
		
		return storageTypeRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public StorageType get(int id) {
		
		return storageTypeRepository.getOne(id);
	}

	public int save(StorageType storageType) {
		String code = storageType.getCode();
		String name = storageType.getName();
		List<StorageType> sc = storageTypeRepository.getByCode(code);
		List<StorageType> sn = storageTypeRepository.getByName(name);
		if(sc.size()>0){
			return 0;
		}
		if(sn.size()>0){
			return -1;
		}
		storageTypeRepository.saveAndFlush(storageType);
		return 1;
	}

	public int update(int id,StorageType storageType) {
		StorageType loadStorageType = storageTypeRepository.getOne(id);
		String code = storageType.getCode();
		String name = storageType.getName();
		List<StorageType> sc = storageTypeRepository.getByCode(code);
		List<StorageType> sn = storageTypeRepository.getByName(name);
		if(sc.size()>0&&!code.equals(loadStorageType.getCode())){
			return 0;
		}
		if(sn.size()>0&&!name.equals(loadStorageType.getName())){
			return -1;
		}
		BeanUtils.copyProperties(storageType, loadStorageType, new String[]{"id"});
		storageTypeRepository.saveAndFlush(loadStorageType);
		return 1;
		
	}

	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Storage_Type", "id", id);
		if(result.equals("")){
			storageTypeRepository.delete(id);
			return "";
		}else{
			return result;
		}
		
	}

	public void deleteBatch(int[] ids) {
		
	 for (int id : ids) {
		storageTypeRepository.delete(id);
	 }
	}

}
